package com.jianyun.jyzs.widget.badge;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;

import java.util.List;


public class HtcBadgeHandler implements IBadgeHandler {

    private Context context;

    private static final String EXTRA_COMPONENT = "com.htc.launcher.extra.COMPONENT";
    private static final String EXTRA_COUNT = "com.htc.launcher.extra.COUNT";
    private static final String INTENT_SET_NOTIFICATION = "com.htc.launcher.action.SET_NOTIFICATION";
    private static final String INTENT_UPDATE_SHORTCUT = "com.htc.launcher.action.UPDATE_SHORTCUT";
    private static final String COUNT = "count";
    private static final String PACKAGENAME = "packagename";
    private ComponentName componentName;

    public HtcBadgeHandler(Context context) {
        this.context = context;
        componentName = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()).getComponent();
    }

    @Override
    public void updateBadgeCount(int count) {
        Intent intent = new Intent(INTENT_SET_NOTIFICATION);
        intent.putExtra(EXTRA_COMPONENT, componentName.flattenToShortString());
        intent.putExtra(EXTRA_COUNT, count);

        Intent intent1 = new Intent(INTENT_UPDATE_SHORTCUT);
        intent1.putExtra(PACKAGENAME, context.getPackageName());
        intent1.putExtra(COUNT, count);

        if (canResolveBroadcast(intent) || canResolveBroadcast(intent1)) {
            context.sendBroadcast(intent);
            context.sendBroadcast(intent1);
        }
    }

    private boolean canResolveBroadcast(Intent intent) {
        PackageManager packageManager = context.getPackageManager();
        List<ResolveInfo> receivers = packageManager.queryBroadcastReceivers(intent, 0);
        return receivers != null && receivers.size() > 0;
    }
}
